<script lang="ts" setup>
import {reactive, ref} from 'vue'
import {ElForm} from 'element-plus'
import {type Login} from '@/api/interface'
import Api from '@/api'
import {useRouter} from 'vue-router'
import useUserStore from '@/store/user.ts'

// 定义 formRef（校验规则）
type FormInstance = InstanceType<typeof ElForm>
const loginFormRef = ref<FormInstance>()
const loginRules = reactive({
	userName: [{required: true, message: '请输入用户名', trigger: 'blur'}],
	password: [{required: true, message: '请输入密码', trigger: 'blur'}]
})
const loading = ref(false)
const userStore = useUserStore()
const loginForm = reactive<Login.ReqLoginForm>({userName: '', password: ''})
const router = useRouter()

const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.resetFields()
}

const login = async (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate(async (valid) => {
		if (!valid) return
		loading.value = true
		try {
			Api.Login(loginForm).then((res: Login.ResLogin) => {
				if (res.code === 200) {
					userStore.setToken(res.data.accessToken)
					userStore.setFreshToken(res.data.refreshToken)
					router.push({path: '/'})
				}
			})
		} finally {
			loading.value = false
		}
	})
}
</script>

<template>
	<el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
		<el-form-item prop="userName">
			<el-input v-model="loginForm.userName" placeholder="用户名：admin / user">
				<template #prefix>
					<base-icon icon="User"/>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item prop="password">
			<el-input
				v-model="loginForm.password"
				autocomplete="new-password"
				placeholder="密码：123456"
				show-password
				type="password"
				@keydown.enter="login(loginFormRef)"
			>
				<template #prefix>
					<el-icon class="el-input__icon">
						<component :is="'lock'"/>
					</el-icon>
				</template>
			</el-input>
		</el-form-item>
	</el-form>
	<div class="login-btn">
		<el-button :icon="'CircleClose'" round size="large" @click="resetForm(loginFormRef)">重置</el-button>
		<el-button :icon="'UserFilled'" :loading="loading" round size="large" type="primary" @click="login(loginFormRef)">
			登录
		</el-button>
	</div>
</template>

<style lang="scss" scoped>
@import "../index.scss";
</style>
